<?php

trait Trait_Api_Search
{


    /**
     * @param $seachkeys
     * @param $keyword
     * @param $typeid
     * @param $startcity
     * @return array
     * User: netman
     * Date: 2023/10/18 9:28
     */
    private function get_search_model($seachkeys, $keyword, $typeid, $startcity = null)
    {
        $out = array();
        $has_search = array();

        //uni端模型
        $search_model = $this->get_uni_search_model();
        $out['all_search_model'] = $search_model;
        foreach ($search_model as $m) {
            //如果不是当前搜索的模块，那么判断是否含有搜索结果
            if ($typeid != $m['typeid']) {
                $model = Model_Model::get_module_info($m['typeid']);
                if ( ! $model['maintable']) {
                    continue;
                }
                $keysearch = ! empty($seachkeys) && ! empty($seachkeys[0]) ? $this->get_keyword_where($model['maintable'],
                    $seachkeys, array('keyword' => $keyword)) : '';

                // var_dump($keysearch);die;
                $where = $this->get_default_where(array('keyword' => $keyword), $keysearch, $model['maintable']);


                if ($this->check_column($model['maintable'], 'ishidden')) {
                    $where .= " and ishidden=0 ";
                }
                if ($model['maintable'] == 'model_archive') {
                    $where .= " and a.typeid={$m['typeid']}";
                }
                if ($m['typeid'] == 11) {
                    $where .= " and a.status=1";
                }
                if ( ! empty($startcity)) {
                    if ( ! $this->check_column($model['maintable'], 'startcity')) {
                        continue;
                    }
                    $startcity_id = DB::select('id')->from('startplace')->where('cityname', '=',
                        $startcity)->execute()->get('id');
                    if ( ! empty($startcity_id)) {
                        $where .= " and a.startcity='{$startcity_id}'";
                    }
                }


                if ($model['maintable']) {
                    $table = 'sline_'.$model['maintable'];
                    $sql = "select a.id from $table as a WHERE  $where limit 1";
                    $list = DB::query(1, $sql)->execute()->as_array();
                    if ($list) {
                        $has_search[] = $m;
                    }
                }
            } else {
                $has_search[] = $m;
            }
        }
        $out['has_search'] = $has_search;
        return $out;
    }

    /**
     * @function 获取可搜索的模块
     * @return mixed
     *  新增 游记 结伴
     */
    private function get_uni_search_model()
    {
        $arr = DB::select(array('a.m_typeid', 'typeid'), array('a.m_title', 'shortname'), 'b.pinyin', 'b.correct',
            'b.issystem')
            ->from(array('m_nav', 'a'))
            ->join(array('model', 'b'))
            ->on('a.m_typeid', '=', 'b.id')
            ->where('a.m_isopen', '=', 1)
            ->and_where('b.isopen', '=', 1)
            ->and_where('a.m_typeid', 'not in', array(7, 9, 10, 12, 14, 105, 21))
            ->order_by('a.m_displayorder', 'asc')
            ->execute()->as_array();

        foreach ($arr as &$r) {
            $r['modulename'] = $r['shortname'];
            $r['id'] = $r['typeid'];
        }
        return $arr;
    }

    /**
     * @function 解析关键词
     * @param $table
     * @param $keyword
     * @return string
     */
    private function get_keyword_where($table, $keyword, $params)
    {
        if (empty($keyword)) {
            return '';
        }
        //过滤特殊字符,防止注入和报错
        $regex = "/\/|\~|\"|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
        $keyword = preg_replace($regex, "", $keyword);
        $keysearch = '';
        $add_column = $this->get_add_column($table);
        //关键字
//        $keyword[] = $params['keyword'];
        $params_keyword = preg_replace($regex, "", $params['keyword']);
        if ($params_keyword) {
            $keyword[] = $params_keyword;
        }
        if (preg_match("/^\d*$/", $keyword[0])) {
            $production_id = Common::getKeyword($keyword[0]);
            $keysearch = " a.id={$production_id} or ";
            //    return $keysearch;
        }
        $keyword = implode('|', $keyword);
        if ($keyword) {
            $keysearch .= "a.title REGEXP '$keyword'";
            if ($add_column) {
                $keysearch .= " or a.$add_column REGEXP '$keyword' ";
            }
        }
        return $keysearch;
    }

    /**
     * @function 获取扩展搜索字段
     * @param $table
     */
    private function get_add_column($table)
    {
        $default_column = array('sellpoint', 'description');
        foreach ($default_column as $column) {
            if ($this->check_column($table, $column)) {
                return $column;
            }
        }
    }

    /**
     * @function 判断字段是否存在
     * @param $tabel
     * @param $column
     */
    private function check_column($tabel, $column)
    {
        $tabel = 'sline_'.$tabel;
        $sql = "show columns from `{$tabel}` like '{$column}'";
        $result = DB::query(1, $sql)->execute()->current();
        if (false === $result) {
            return false;
        } else {
            return count($result) > 0 ? true : false;
        }
    }

    /**
     * 获取默认的搜索条件 关键词，目的地，属性
     * @function
     */
    private function get_default_where($params, $keysearch, $table)
    {
        $where = " a.id>0";
        //关键词
        if ($keysearch) {
            $where .= " and ($keysearch)";
        }

        $cfg_city_site_type = Model_Sysconfig::get_configs(0, 'cfg_city_site_type', true);
        $city = Cookie::get('current_city', '选择城市');
        if ( ! empty($city)) {
            //如果是出发地
            if ($cfg_city_site_type == 1 && $this->check_column($table, 'startcity')) {
                $startcity_id = DB::select('id')->from('startplace')->where('cityname', '=',
                    $city)->execute()->get('id');
                if ( ! empty($startcity_id)) {
                    $where .= " and a.startcity='{$startcity_id}'";
                }
            } else {
                if ($cfg_city_site_type != 1) {
                    $destid = DB::select('id')->from('destinations')->where('kindname', '=',
                        $city)->execute()->get('id');
                    if ($destid && $this->check_column($table, 'kindlist')) {
                        $where .= " and find_in_set($destid,a.kindlist)";
                    }
                }
            }
        }
        //目的地
        if ($params['destid'] && $this->check_column($table, 'kindlist')) {
            $where .= " and find_in_set({$params['destid']},a.kindlist)";
        }
        //属性
        if ($this->check_column($table, 'attrid')) {
            foreach ($params['attrlist'] as $attr) {
                if ($attr) {
                    $where .= " and find_in_set($attr,a.attrid)";
                }
            }
        }
        return $where;
    }


}